#include <mysql/mysql.h>
#include <iostream>
#include <string>

const std::string host = "localhost";
const std::string user = "connector";
const std::string password = "5397687p";
const std::string db = "conn";
const unsigned int port = 3306; // 确认你的MySQL服务器是否在3306端口上运行

int main() {
    MYSQL* my = mysql_init(nullptr);
    if (my == nullptr) {
        std::cout << "MySQL initialization failed" << std::endl;
        return 1;
    }

    if (mysql_real_connect(my, host.c_str(), user.c_str(), password.c_str(), db.c_str(), port, nullptr, 0) == nullptr) {
        std::cout << "Connection error: " << mysql_error(my) << std::endl;
        mysql_close(my);
        return 1;
    }

    std::string sql;
    while (true) {
        std::cout << ">> ";
        if (!std::getline(std::cin, sql)) break;
        if (sql == "quit") break;

        int n = mysql_query(my, sql.c_str());
        if (n == 0) {
            std::cout << "Success" << std::endl;

            // 处理查询结果
            if (MYSQL_RES* res = mysql_store_result(my)) {
                int num_fields = mysql_num_fields(res);
                MYSQL_ROW row;
                while ((row = mysql_fetch_row(res))) {
                    for (int i = 0; i < num_fields; ++i) {
                        std::cout << (row[i] ? row[i] : "NULL") << " ";
                    }
                    std::cout << std::endl;
                }
                mysql_free_result(res);
            }
        } else {
            std::cout << "Query failed: " << mysql_error(my) << std::endl;
        }
    }

    mysql_close(my);
    return 0;
}
